﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using MyHelper;
using HandyControl.Controls;
using HandyControl.Tools;
using System.Windows.Media.Animation;
using System.Threading;
using System.ComponentModel;
using System.Windows.Controls.Primitives;
using System.Windows.Interop;
using System.Collections.ObjectModel;
using clf.weighing.entity;

using ComboBox = HandyControl.Controls.ComboBox;
using TextBox = HandyControl.Controls.TextBox;
using Brushes = System.Windows.Media.Brushes;
using System.Diagnostics;

namespace weighing
{
    /// <summary>
    /// InputWeighingContent.xaml 入库过磅 的交互逻辑
    /// </summary>
    public partial class InputWeighingContent : WeighingUserContent
    {
        #region variabes      
        protected bool isSaveing = false;
        private List<WeighingBillVo>? noOutBills;
        private System.Timers.Timer? mTimer;
        /// <summary>
        /// 读取磅称的是否提示
        /// </summary>
        private bool isSaleAlert = true;
        private double currTonner = 0;
        #endregion

        public InputWeighingContent()
        {
            InitializeComponent();
            if (DesignerProperties.GetIsInDesignMode(this)) return;
            currBillType = WeightingBillType.Buy;
            this.Loaded += InputWeighingContent_Loaded;
            this.Unloaded += InputWeighingContent_Unloaded;
            this.IsVisibleChanged += InputWeighingContent_IsVisibleChanged;
        }

        private void InputWeighingContent_Loaded(object sender, RoutedEventArgs e)
        {
            this.currHouseTb.Text = App.CurrentScaleHouseVo?.Name ?? "      ";
            this.billnumberTb.IsReadOnly = App.Config.BillPrintConfig.AutoGeneretor;
            this.billnumberTb.IsEnabled = !App.Config.BillPrintConfig.AutoGeneretor;

            AddBackFieldControl(this.inputCanvas);

            mWeighingBill = new WeighingBill();

            InitLockSendBtn();
            InitLockReceiveBtn();
            InitLockMaterialBtn();

            RegistryDelegete();

            ShowOrHidePricePanel();

            //将本机使用的基础数据设置默认数据源 
            SetDefaultSource();

            SetWeihinger();
            this.inFactoryRb.IsChecked = true;
            //过磅设置界面是否显示 必须的红点
            this.InWeighingGrid.DataContext = App.Config.WeighingConfig;
            //显示磅差等 
            ShowDecuationWeightView();

            InitTimer();

            mTimer?.Start();

            HandleIgnoreTraeWeighing();
        }

        private void HandleIgnoreTraeWeighing()
        {
            if (App.Config.WeighingConfig.Times == 1 && App.Config.WeighingConfig.InIgnoreTraeWeighing)
            {
                this.TraeWeightTb.Text = "0";
                this.TraeWeightTb.Visibility = Visibility.Collapsed;
            }
            else
            {
                this.TraeWeightTb.Text = "0";
                this.TraeWeightTb.Visibility = Visibility.Visible;
            }
        }
        private void InitTimer()
        {
            if (mTimer == null)
            {
                mTimer = new System.Timers.Timer(1000);
                mTimer.BeginInit();
                mTimer.Elapsed += (obj, args) =>
                {
                    this.Dispatcher.Invoke(new Action(delegate
                    {
                        ReadScaleData();
                    }));
                };
                mTimer.EndInit();
            }
        }
        private void InputWeighingContent_Unloaded(object sender, RoutedEventArgs e)
        {
            if (mTimer != null)
            {
                mTimer?.Stop();
                mTimer?.Dispose();
            }

            ClearDelegete();
        }

        private void InputWeighingContent_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (this.IsLoaded == false) return;
            if (this.IsVisible == true && this.Visibility == Visibility.Visible)//显示
            {
                //读取磅称数据                
                mTimer?.Start();
            }
            else
            {
                //停止读取磅称数据
                mTimer?.Stop();

                ClearCarInfo();
                // 停止模拟数据 
                this.moniWeighingCb.IsChecked = false;
            }
        }

        #region visibility change handle


        private void ClearCarInfo()
        {
            this.carNumberCb.Text = "";
        }
        #endregion

        /// <summary>
        /// 读取磅称数据 
        /// </summary>
        private void ReadScaleData()
        {
            MainWindow? mw = App.Current.MainWindow as MainWindow;
            ScaleVo? vo = mw?.ScaleContentUc.GetCurrentScale(currBillType);

            if (vo == null)
            {
                string msg = "没有指定磅秤\n请点击上方的磅称，或者去设置默认";
                if (isSaleAlert)
                {
                    var result = CommonFunction.Ask(msg);
                    if (result == MessageBoxResult.Yes)
                    {
                        isSaleAlert = false;
                    }
                }
                return;
            }
            int digits = App.Config.WeighingConfig.Digits;
            var tonner = vo.Tonner;
            currTonner = tonner;
            if (App.Config.WeighingConfig.Times == 2)
            {
                //出场
                if (isOutFactory)
                {
                    this.TraeWeightTb.Text = tonner.ToString();
                }
                else
                {
                    // 入场
                    this.grossWeightTb.Text = tonner.ToString();
                }
            }
            else
            {
                this.grossWeightTb.Text = tonner.ToString();
            }
        }

        #region 将本机使用的基础数据设置默认数据源 最新使用的排在最前面
        /// <summary>
        /// 将本机使用的基础数据设置默认数据源 
        /// </summary>
        private void SetDefaultSource()
        {
            var companyS = CompanyDao.Instance.GetList().Select(i => { return new CompanyVo(i); }).ToList();
            var ms = MaterialDao.Instance.GetList().Select(i => { return new MaterialVo(i); }).ToList();
            var cars = CarDao.Instance.GetList().Select(i => { return new CarInfoVo(i); }).ToList();
            this.sendCompanyCb.ItemsSource = companyS;
            this.RecevieCompanyCb.ItemsSource = companyS;
            this.materialCb.ItemsSource = ms;
            this.carNumberCb.ItemsSource = cars;

            CommonFunction.SetDecuationItemSource(this.decuDescCb);
            CommonFunction.SetRemarkItemSource(this.remarkCb);
        }

        #endregion


        private void InFactoryRb_Checked(object sender, RoutedEventArgs e)
        {
            if (this.IsLoaded == false) { return; }
            Storyboard storyboard = new Storyboard();
            var anim = AnimationHelper.CreateAnimation(this.waitOutputBorder.ActualWidth);// enter from right
            Storyboard.SetTarget(anim, this.waitOutputBorder);
            Storyboard.SetTargetProperty(anim, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.X)"));
            storyboard.Children.Add(anim);

            var leftAni = AnimationHelper.CreateAnimation(0);
            //Storyboard.SetTarget(leftAni, this.inputPanel);
            Storyboard.SetTarget(leftAni, this.inputCanvas);
            Storyboard.SetTargetProperty(leftAni, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.X)"));
            storyboard.Children.Add(leftAni);
            storyboard.Begin();

            mWeighingBill = null;
            IsInsert = true;

            ShowDecuationWeightView();

            BuildCurrWeighingBill();

            SetDfaultCompany();
        }


        private void OutFactoryRb_Checked(object sender, RoutedEventArgs e)
        {
            if (this.IsLoaded == false || IsRecongnizePlateWeighing == true) { return; }
            Storyboard storyboard = new Storyboard();
            var anim = AnimationHelper.CreateAnimation(0);// enter from right
            Storyboard.SetTarget(anim, this.waitOutputBorder);
            Storyboard.SetTargetProperty(anim, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.X)"));
            storyboard.Children.Add(anim);

            var leftAni = AnimationHelper.CreateAnimation(-this.waitOutputBorder.ActualWidth);
            //Storyboard.SetTarget(leftAni, this.inputPanel);
            Storyboard.SetTarget(leftAni, this.inputCanvas);
            Storyboard.SetTargetProperty(leftAni, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.X)"));
            storyboard.Children.Add(leftAni);
            storyboard.Completed += Storyboard_Completed;
            storyboard.Begin();
            IsInsert = false;
        }

        //车辆出场
        private void Storyboard_Completed(object sender, EventArgs e)
        {
            var list = WeighingBillDao.Instance.GetNoOutBills(currBillType);
            noOutBills = list?.Select((i) => { return new WeighingBillVo(i); }).ToList();
            this.waitOutLv.ItemsSource = null;
            this.waitOutLv.ItemsSource = noOutBills;
            this.noOutCars.Text = noOutBills?.Count.ToString() ?? "0";

            ShowDecuationWeightView();


            ShowOrHidePricePanel();
        }

        /// <summary>
        /// 设置出入库是的默认公司 
        /// </summary>
        public void SetDfaultCompany()
        {
            // 锁定收货方 或者 监管模式 优化
            if (App.Config.WeighingConfig.InBindingReceive)
            {
                this.receiverCompanyVo = App.CurrentCompanyVo;
                this.RecevieCompanyCb.IsEnabled = false;
                this.RecevieCompanyCb.IsDropDownOpen = false;
                this.isSelectReceiveCompany = true;
                this.lockReceiveBtn.IsEnabled = false;
                this.RecevieCompanyCb.Text = App.CurrentCompanyVo?.FullName;
                this.mWeighingBill.receiveCompanyId = App.CurrentCompanyVo?.Id;
                this.mWeighingBill.receiveCompanyName = App.CurrentCompanyVo?.FullName;
            }
            else
            {
                this.lockReceiveBtn.IsEnabled = true;
                //临时锁定
                if (App.Config.WeighingConfig.InLockReceiveCompany && LockData.Instance.InLockReceive != null)
                {
                    this.RecevieCompanyCb.IsEnabled = false;
                    this.RecevieCompanyCb.Text = LockData.Instance.InLockReceive.FullName;
                }
                else
                {
                    this.receiverCompanyVo = null;
                    this.RecevieCompanyCb.IsEnabled = true;
                    this.isSelectReceiveCompany = false;
                    this.RecevieCompanyCb.Text = "";
                    this.mWeighingBill.receiveCompanyId = 0;
                    this.mWeighingBill.receiveCompanyName = "";
                }
            }
        }

        /// <summary>
        /// 构建当前的磅单
        /// </summary>
        private void BuildCurrWeighingBill()
        {
            if (mWeighingBill == null)
            {
                // in factoty
                isOutFactory = false;
                currBillNumber = GetWeighingNumber();
                this.billnumberTb.Text = currBillNumber;

                mWeighingBill = new WeighingBill()
                {
                    id = IdHelper.LongID,
                    number = currBillNumber,
                    type = (int)currBillType,
                    userId = App.CurrentUser?.id ?? 0,
                    affiliatedCompanyId = App.CurrentCompanyVo?.Id ?? 0,
                    receiveStatus = 0,
                    unitText = App.UnitText,
                    isDelete = 0,
                    isChangeCompany = false,
                    houseId = App.CurrentScaleHouseVo?.Id ?? 0,
                    houseName = App.CurrentScaleHouseVo?.Name ?? "",
                    inUserName = App.CurrentUser?.name ?? ""
                };

                SetHouseInfo();

                #region 恢复控件状态
                SetDfaultCompany();

                if (App.Config.WeighingConfig.InLockSendCompany && LockData.Instance.InLockSend != null)
                {
                    this.sendCompanyCb.IsEnabled = false;
                    this.sendCompanyCb.Text = LockData.Instance.InLockSend.FullName;
                }
                else
                {
                    this.sendCompanyCb.IsEnabled = true;
                    this.sendCompanyCb.Text = string.Empty;
                }

                if (App.Config.WeighingConfig.InLockMaterial && LockData.Instance.InLockMaterial != null)
                {
                    this.materialCb.IsEnabled = false;
                    this.materialCb.Text = LockData.Instance.InLockMaterial.Name;
                }
                else
                {
                    this.materialCb.IsEnabled = true;
                    this.materialCb.Text = string.Empty;
                }
                this.TranceCompanyCb.Text = string.Empty;
                this.TempPriceTb.Text = String.Empty;
                this.carNumberCb.Text = string.Empty;
                this.driverTb.Text = string.Empty;
                this.phoneTb.Text = string.Empty;

                this.sendNetWeightTb.Text = "0";
                this.grossWeightTb.Text = "0";
                this.TraeWeightTb.Text = "0";
                this.netWeightTb.Text = "0";
                this.decuationWeightTb.Text = "0";
                this.diffWeightTb.Text = "0";

                this.carNumberCb.IsEnabled = true;
                this.isCarInfoSelectioned = false;

                ClearBackFieldValue();
                this.remarkCb.Text = string.Empty;
                this.remarkCb.SelectedIndex = -1;
                #endregion
            }
            else
            {
                //out factoty
                isOutFactory = true;
                #region 设置控件值
                isBindingValue = true;
                this.billnumberTb.Text = mWeighingBill.number;
                this.sendCompanyCb.Text = mWeighingBill.sendCompanyName;
                this.RecevieCompanyCb.Text = mWeighingBill.receiveCompanyName;
                this.TranceCompanyCb.Text = mWeighingBill.tranceCompanyName;
                this.isCarInfoSelectioned = true;
                this.carNumberCb.Text = mWeighingBill.carNumber;
                this.driverTb.Text = mWeighingBill.driver;
                this.phoneTb.Text = mWeighingBill.driverMobile;
                this.materialCb.Text = mWeighingBill.materialName;
                this.sendNetWeightTb.Text = mWeighingBill.sendNetWeight.ToString();
                this.grossWeightTb.Text = mWeighingBill.grossWeight.ToString();
                this.TraeWeightTb.Text = mWeighingBill.traeWeight.ToString();
                this.netWeightTb.Text = mWeighingBill.netWeight.ToString();
                this.remarkCb.Text = mWeighingBill.remark;
                this.TempPriceTb.Text = mWeighingBill.price.ToString();

                SetterBackFieldValue(mWeighingBill);

                SetMaterialPrice();
                isBindingValue = false;
                #endregion
            }
            ShowOrHidePricePanel();
        }

        /// <summary>
        /// 计算收货吨位  calculating the tonnage of receipt
        /// </summary>
        private void CalcReceiptWeightValue()
        {
            if (this.IsLoaded == false || this.IsVisible == false) return;

            //一次过磅就是出场
            if (App.Config.WeighingConfig.Times == 1)
            {
                OutFactoryCalculate();
                return;
            }
            if (isOutFactory)
            {
                decimal gross = mWeighingBill?.grossWeight ?? 0;
                decimal trae = 0;
                decimal decuation = 0;
                decimal net;
                // decimal sendnet = (decimal)mWeighingBill.SendNetWeight;
                decimal sendnet = 0;
                try { sendnet = Convert.ToDecimal(this.sendNetWeightTb.Text); } catch { }
                decimal diff;
                try { trae = Convert.ToDecimal(this.TraeWeightTb.Text); } catch { }
                try { decuation = Convert.ToDecimal(this.decuationWeightTb.Text); } catch { }
                net = gross - trae - decuation;
                this.netWeightTb.Text = net.ToString();
                diff = Math.Round(net - sendnet, 2);
                this.diffWeightTb.Text = diff.ToString();
                mWeighingBill.traeWeight = trae;
                mWeighingBill.decuationWeight = decuation;
                mWeighingBill.netWeight = net;
                mWeighingBill.diffWeight = diff;
            }
            else
            {
                InFactoryCalculate();
            }

        }
        //出场计算
        private void OutFactoryCalculate()
        {
            decimal gross = 0;
            decimal trae = 0;
            decimal decuation = 0;
            decimal net;
            decimal sendnet = 0;
            decimal diff;
            try { gross = Convert.ToDecimal(this.grossWeightTb.Text); } catch { }
            try { sendnet = Convert.ToDecimal(this.sendNetWeightTb.Text); } catch { }
            try { decuation = Convert.ToDecimal(this.decuationWeightTb.Text); } catch { }

            try
            {
                trae = Convert.ToDecimal(this.TraeWeightTb.Text);
            }
            catch { }

            try { decuation = Convert.ToDecimal(this.decuationWeightTb.Text); } catch { }
            net = gross - trae - decuation;
            this.netWeightTb.Text = net.ToString();
            diff = Math.Round(net - sendnet, 2);
            this.diffWeightTb.Text = diff.ToString();

            mWeighingBill.grossWeight = gross;
            mWeighingBill.traeWeight = trae;
            mWeighingBill.decuationWeight = decuation;
            mWeighingBill.netWeight = net;
            mWeighingBill.diffWeight = diff;
            mWeighingBill.sendNetWeight = sendnet;
        }
        //入场计算
        private void InFactoryCalculate()
        {
            decimal gross = 0;
            decimal trae = 0;
            decimal decuation = 0;
            decimal net;
            decimal sendnet = 0.0M;
            decimal diff;
            try { gross = Convert.ToDecimal(this.grossWeightTb.Text); } catch { }
            try { trae = Convert.ToDecimal(this.TraeWeightTb.Text); } catch { }
            try { sendnet = Convert.ToDecimal(this.sendNetWeightTb.Text); } catch { }
            net = gross - trae - decuation;
            this.netWeightTb.Text = net.ToString();
            diff = Math.Round(net - sendnet, 2);

            mWeighingBill.decuationWeight = decuation;
            mWeighingBill.grossWeight = gross;
            mWeighingBill.traeWeight = trae;
            mWeighingBill.netWeight = net;
            mWeighingBill.diffWeight = diff;
            mWeighingBill.sendNetWeight = sendnet;
        }

        //只能输入数字
        private void Number_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || (e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.Back || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Decimal)
            {
                if (e.KeyboardDevice.Modifiers != ModifierKeys.None)
                {
                    e.Handled = true;
                }
            }
            else
            {
                e.Handled = true;
            }
        }

        #region TextBox 改变事件

        //原发净重
        private void SendNetWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcReceiptWeightValue();
        }
        //扣重
        private void DecuationWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (RegexHelper.IsNumber(this.decuationWeightTb.Text))
            {
                CalcReceiptWeightValue();
            }
            else
            {
                CommonFunction.AlertInfo("扣重只能输入数字");
                this.decuationWeightTb.Text = "0";
            }

        }
        private void GrossWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcReceiptWeightValue();
        }

        private void TraeWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcReceiptWeightValue();
        }
        private void NetWeightTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            CalcReceiptWeightValue();
            CalcMaterialMoney();
        }
        #endregion

        #region  磅房信息

        /// <summary>
        /// 设置磅房信息
        /// </summary>
        private void SetHouseInfo()
        {
            if (App.CurrentScaleHouseVo != null)
            {
                mWeighingBill.houseId = App.CurrentScaleHouseVo.Id;
                mWeighingBill.houseName = App.CurrentScaleHouseVo.Name;
            }
        }
        #endregion

        #region Supply 
        private bool isSupplySelected = false;
        private void SupplyCb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (isBindingValue == true) return;

            //In Necessary Send  not must ,not to search
            if (App.Config.WeighingConfig.InNecessarySend == false) return;

            String text = this.sendCompanyCb.Text.Trim();
            if (text.Length < 2)
            {
                isSupplySelected = false;
                this.sendCompanyCb.IsDropDownOpen = false;
            }
            if (isSupplySelected == true)
            {
                return;
            }
            if (text.Length >= 2)
            {
                List<Company> list = CompanyDao.Instance.SelectByNameOrFirstCaseLike(text);
                var data = list?.Select((i) => { return new CompanyVo(i); });
                isSupplySelected = list?.Count > 0;
                this.sendCompanyCb.ItemsSource = data;
                this.sendCompanyCb.IsDropDownOpen = list.Count > 0;
            }
            else
            {
                this.sendCompanyCb.ItemsSource = null;
                this.sendCompanyCb.ItemsSource = RuntimeData.Instance.TempCompany.ToList();
            }
        }
        private void SupplyCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sendCompanyCb.SelectedIndex == -1)
            {
                this.sendCompanyCb.Text = "";
                sendCompanyVo = null;
                return;
            }
            isSupplySelected = true;
            sendCompanyVo = sendCompanyCb.SelectedItem as CompanyVo;
            if (sendCompanyVo != null)
            {
                if (CheckSupplyCustomer(WeightingBillType.Buy) == false)
                {
                    string msg = "发货公司和收货公司不能是同一个！";
                    CommonFunction.SpeakAsync(msg);
                    CommonFunction.AlertInfo(msg);
                    sendCompanyCb.SelectedIndex = -1;
                    this.sendCompanyCb.Text = "";
                    sendCompanyVo = null;
                }
                else
                {
                    mWeighingBill.sendCompanyId = sendCompanyVo.Id;
                    mWeighingBill.sendCompanyName = sendCompanyVo.FullName;
                }

            }
        }

        #endregion


        #region Receiver Company
        private bool isSelectReceiveCompany = false;
        private void ReceiverCompanyCb_TextChanged(object sender, TextChangedEventArgs e)
        {
            // if (isAllowDiffrenceCompany == false) { return; }
            if (isBindingValue == true) return;
            //In Necessary Receive  not must ,not to search
            if (App.Config.WeighingConfig.InNecessaryReceive == false) return;

            String text = this.RecevieCompanyCb.Text.Trim();
            if (text.Length < 2)
            {
                isSelectReceiveCompany = false;
                this.RecevieCompanyCb.IsDropDownOpen = false;
            }
            if (isSelectReceiveCompany == true) { return; }
            if (text.Length >= 2)
            {
                List<Company> list = CompanyDao.Instance.SelectByNameOrFirstCaseLike(text);
                var data = list?.Select((i) => { return new CompanyVo(i); }).ToList();
                isSelectReceiveCompany = list.Count > 0;
                this.RecevieCompanyCb.ItemsSource = data;
                if (this.RecevieCompanyCb.ItemsSource != null)
                {
                    this.RecevieCompanyCb.IsDropDownOpen = true;
                }
                else
                {
                    this.RecevieCompanyCb.IsDropDownOpen = false;
                }
            }
            else
            {
                this.RecevieCompanyCb.ItemsSource = null;
                this.RecevieCompanyCb.ItemsSource = RuntimeData.Instance.TempCompany.ToList();
            }
        }
        private void ReceiverCompanyCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (RecevieCompanyCb.SelectedIndex == -1)
            {
                RecevieCompanyCb.Text = "";
                receiverCompanyVo = null;
                return;
            };
            isSelectReceiveCompany = true;
            receiverCompanyVo = RecevieCompanyCb.SelectedItem as CompanyVo;
            if (receiverCompanyVo != null)
            {
                if (CheckSupplyCustomer(WeightingBillType.Buy) == false)
                {
                    string msg = "发货公司和收货公司不能是同一个！";
                    CommonFunction.SpeakAsync(msg);
                    CommonFunction.AlertInfo(msg);
                    RecevieCompanyCb.SelectedIndex = -1;
                    RecevieCompanyCb.Text = "";
                }
                else
                {
                    mWeighingBill.receiveCompanyId = receiverCompanyVo.Id;
                    mWeighingBill.receiveCompanyName = receiverCompanyVo.FullName;
                }

            }
        }

        #endregion

        #region Material 
        private bool isSelectMaterial = false;
        private void MaterialNameCb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (isBindingValue == true) return;
            if (App.Config.WeighingConfig.InNecessaryMaterial == false) return;

            String text = this.materialCb.Text.Trim();
            if (text.Length < 2)
            {
                isSelectMaterial = false;
                this.materialCb.IsDropDownOpen = false;
                this.materialCb.SelectedIndex = -1;
            }
            if (isSelectMaterial == true) { return; }
            if (text.Length >= 2)
            {
                List<Material> list = MaterialDao.Instance.SelectByNameOrFirstCaseLike(text);
                var data = list?.Select((i) => { return new MaterialVo(i); }).ToList();
                this.materialCb.ItemsSource = data;
                if (list?.Count > 0) isSelectMaterial = true;
                if (this.materialCb.ItemsSource != null)
                {
                    this.materialCb.IsDropDownOpen = true;
                }
                else
                {
                    this.materialCb.IsDropDownOpen = false;
                }
            }
            else
            {
                this.materialCb.ItemsSource = null;
                this.materialCb.ItemsSource = RuntimeData.Instance.TempMaterial.ToList();
            }
        }

        private void MaterialNameCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (materialCb.SelectedIndex > -1)
            {
                isSelectMaterial = true;
                currMaterialVo = materialCb.SelectedItem as MaterialVo;
                mWeighingBill.materialId = currMaterialVo?.Id;
                mWeighingBill.materialName = currMaterialVo?.Name;
                if (App.Config.WeighingConfig.Times == 1)
                {
                    SetMaterialPrice();
                }
            }
            else
            {
                isSelectMaterial = false;
                currMaterialVo = null;
                if (!isOutFactory)
                {
                    mWeighingBill.materialId = null;
                    mWeighingBill.materialName = null;
                }
            }
        }
        #endregion

        #region CarInfo Selection
        private bool isCarInfoSelectioned = false;
        private void CarNumberCb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (isBindingValue == true) return;
            String text = this.carNumberCb.Text.Trim();
            if (text.Length <= 1)
            {
                isCarInfoSelectioned = false;
                currCarVo = null;
                this.carNumberCb.SelectedItem = null;
                this.carNumberCb.IsDropDownOpen = false;
                SetCarInfo();
                return;
            }
            //in Necessary Car  not must ,not to search
            if (App.Config.WeighingConfig.InNecessaryCar == false) return;

            if (isCarInfoSelectioned == true) { return; }

            if (text.Length >= 2)
            {
                List<CarInfo> list = CarDao.Instance.SelectByLike(text);
                var data = list?.Select((i) => { return new CarInfoVo(i); }).ToList();
                this.carNumberCb.ItemsSource = data;
                //isCarInfoSelectioned = list.Count > 0;
                if (carNumberCb.ItemsSource != null)
                {
                    //是一个正常的车牌或者 通过识别得到
                    if (RegexHelper.IsVehicleNumber(text))
                    {
                        this.carNumberCb.SelectedIndex = 0;
                        this.carNumberCb.IsDropDownOpen = false;
                    }
                    else
                    {
                        this.carNumberCb.IsDropDownOpen = true;
                        CommonFunction.MoveCursorToLast(this.carNumberCb, this.carNumberCb.Text.Length);

                    }
                }
                else
                {
                    this.carNumberCb.IsDropDownOpen = false;
                    //是一个正常的车牌或者 通过识别得到
                    if (RegexHelper.IsVehicleNumber(text))
                    {
                        isCarInfoSelectioned = true;
                    }
                    this.carNumberCb.ItemsSource = null;
                }
            }
            else
            {
                this.carNumberCb.ItemsSource = RuntimeData.Instance.TempCars?.ToList();
            }
        }

        private void CarNumberCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!IsLoaded) return;
            isCarInfoSelectioned = carNumberCb.SelectedIndex >= 0;
            if (isCarInfoSelectioned)
            {
                currCarVo = carNumberCb.SelectedItem as CarInfoVo;
            }
            else
            {
                currCarVo = null;
            }
            SetCarInfo();
        }

        private void SetCarInfo()
        {
            if (currCarVo != null)
            {
                this.driverTb.Text = currCarVo.Driver;
                this.phoneTb.Text = currCarVo.DriverMobile;
                mWeighingBill.carNumber = currCarVo.CarNumber;
                mWeighingBill.carId = currCarVo.Id;
                mWeighingBill.driver = currCarVo.Driver;
                //mWeighingBill.driverIdNumber = car.driverIdnumber;
                mWeighingBill.driverMobile = currCarVo.DriverMobile;
                if (App.Config.WeighingConfig.Times == 1)
                {
                    if (App.Config.WeighingConfig.InIgnoreTraeWeighing == false)
                    {
                        this.TraeWeightTb.Text = App.Config.WeighingConfig.Unit == Unit.Tone ? currCarVo.TraeWeight.ToString() : (currCarVo.TraeWeight * 1000).ToString();
                    }
                }
            }
            else
            {
                mWeighingBill.carNumber = String.Empty;
                mWeighingBill.carId = 0;
                mWeighingBill.driver = String.Empty;
                this.driverTb.Text = string.Empty;
                this.phoneTb.Text = string.Empty;
                if (App.Config.WeighingConfig.Times == 1)
                {
                    this.TraeWeightTb.Text = "0";
                }
            }
        }
        #endregion

        #region Weihinger
        private void SetWeihinger()
        {
            this.userTb.Text = App.CurrentUser?.name;
            mWeighingBill.userId = App.CurrentUser.id;
            mWeighingBill.inUserName = App.CurrentUser.name;
            this.userTb.Text = App.CurrentUser.name;
        }
        #endregion

        #region remark

        private void RemardTbox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (IsLoaded == false) { return; }
            string value = this.remarkCb.Text;
            mWeighingBill.remark = value;
        }
        #endregion

        #region decuation description
        private void DecuationDescriptionTbox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (this.IsLoaded == false) return;
            mWeighingBill.decuationDescription = this.decuDescCb.Text;
        }
        #endregion

        #region save
        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {

            bool active = App.initConfig?.ActiveType == ActiveType.Code
                ? ActiveCodeHelper.IsSoftActive()
                : ActiveDongleHelper.IsActived();

            if (!active && App.NoActiveLimits > Constant.Limits)
            {
                string msg = $"软件未激活，过磅次数已达到上限 :{Constant.Limits} 条";
                Growl.Error(msg, "main");
                CommonFunction.AlertInfo(msg);
                CommonFunction.SpeakAsync(msg);
                this.saveBtn.IsChecked = false;
                return;
            }


            if (isSaveing)
            {
                isSaveing = false;
                this.saveBtn.IsChecked = false;
                return;
            }
            this.saveBtn.IsChecked = true;
            if (CheckInput() == true)
            {
                isSaveing = true;
                if (IsInsert == true)
                {
                    Insert();
                }
                else
                {
                    Update();
                }
            }
            isSaveing = false;
            this.saveBtn.IsChecked = false;
            //使用线程更新 扣重说明
            UpdateDecuationList();
            //使用线程更新 备注 
            UpdateRemark();
        }


        private bool CheckInput()
        {
            #region 磅单编号
            if (App.Config.BillPrintConfig.AutoGeneretor == false)
            {
                var temp = this.billnumberTb.Text?.Trim();
                if (temp.IsNullOrEmpty())
                {
                    Growl.Warning("请手动输入一个唯一的磅单编号", "main");
                    this.billnumberTb.Focus();
                    this.saveBtn.IsChecked = false;
                    return false;
                }
                mWeighingBill.number = temp;
            }
            #endregion

            if (App.Config.WeighingConfig.InLockSendCompany && sendCompanyVo != null)
            {
                mWeighingBill.sendCompanyId = sendCompanyVo.Id;
                mWeighingBill.sendCompanyName = sendCompanyVo.FullName;
            }

            if (App.Config.WeighingConfig.InNecessarySend)
            {
                if (mWeighingBill.sendCompanyId == null || mWeighingBill.sendCompanyId <= 0 || mWeighingBill.sendCompanyName.IsNullOrEmpty())
                {
                    string msg = "请选择发货公司信息";
                    Growl.Warning(msg, "main");
                    this.sendCompanyCb.Focus();
                    CommonFunction.SpeakAsync(msg);
                    this.saveBtn.IsChecked = false;
                    return false;
                }
            }
            else
            {
                var temp = this.sendCompanyCb.Text;
                if (!temp.IsNullOrEmpty())
                {
                    mWeighingBill.sendCompanyId = 0;
                    mWeighingBill.sendCompanyName = temp.Trim();
                }
            }




            if (App.Config.WeighingConfig.InLockReceiveCompany && receiverCompanyVo != null)
            {
                mWeighingBill.receiveCompanyId = receiverCompanyVo.Id;
                mWeighingBill.receiveCompanyName = receiverCompanyVo.FullName;
            }

            if (App.Config.WeighingConfig.InNecessaryReceive)
            {
                if (mWeighingBill.receiveCompanyId == null || mWeighingBill.receiveCompanyId <= 0 || string.IsNullOrEmpty(mWeighingBill.receiveCompanyName))
                {
                    string msg = "请选择收货公司";
                    Growl.Warning(msg, "main");
                    this.RecevieCompanyCb.Focus();
                    CommonFunction.SpeakAsync(msg);
                    this.saveBtn.IsChecked = false;
                    return false;
                }
            }
            else
            {
                var temp = this.RecevieCompanyCb.Text;
                if (!temp.IsNullOrEmpty())
                {
                    mWeighingBill.receiveCompanyId = 0;
                    mWeighingBill.receiveCompanyName = temp.Trim();
                }
            }


            //运输公司
            if (App.Config.WeighingConfig.InNecessaryTranceCompany)
            {
                if (mWeighingBill?.tranceCompanyId == 0 || string.IsNullOrEmpty(mWeighingBill?.tranceCompanyName))
                {
                    this.TranceCompanyCb.Text = string.Empty;
                    this.TranceCompanyCb.Focus();
                    string msg = "请选运输公司";
                    Growl.Warning(msg, "main");
                    return false;
                }
            }

            if (tranceCompanyVo != null)
            {
                mWeighingBill.tranceCompanyId = tranceCompanyVo.Id;
                mWeighingBill.tranceCompanyName = tranceCompanyVo.FullName;
            }
            else
            {
                mWeighingBill.tranceCompanyId = 0;
                mWeighingBill.tranceCompanyName = String.Empty;
            }

            if (App.Config.WeighingConfig.InLockMaterial && currMaterialVo != null)
            {
                mWeighingBill.materialId = currMaterialVo.Id;
                mWeighingBill.materialName = currMaterialVo.Name;
            }
            //物资
            if (App.Config.WeighingConfig.InNecessaryMaterial)
            {
                if (mWeighingBill.materialId == null || mWeighingBill.materialId <= 0 || string.IsNullOrEmpty(mWeighingBill.materialName))
                {
                    if (this.materialCb.Text.Length > 0)
                    {
                        string m = this.materialCb.Text.Trim();
                        String msg = $"是否要将 {m} 作为物料信息过磅？";
                        var result = CommonFunction.Ask(msg);
                        if (result == MessageBoxResult.Yes)
                        {
                            var material = new Material()
                            {
                                id = IdHelper.LongID,
                                name = m,
                                firstCase = StringHelper.GetFirstPinyin(m),
                                status = 1,
                                categoryId = 0,
                                affiliatedCompanyId = App.CurrentCompanyVo?.Id,
                                addTime = DateTime.Now,
                                belong = (int)DataBelong.Enterprise,
                                syncTime = DateTimeHelper.GetTimeStamp(),
                            };
                            if (currMaterialVo == null)
                            {
                                currMaterialVo = new MaterialVo(material);
                            }
                            mWeighingBill.materialId = currMaterialVo.Id;
                            mWeighingBill.materialName = currMaterialVo.Name;
                        }
                        else
                        {
                            CommonFunction.AlertInfo("物资名称为必须项目，请选择物资名称。");
                            this.materialCb.Focus();
                            return false;
                        }
                    }
                    else
                    {
                        string msg = "请选择物资名称";
                        Growl.Clear();
                        Growl.Warning(msg, "main");
                        this.materialCb.Focus();
                        CommonFunction.SpeakAsync(msg);
                        return false;
                    }
                }

            }
            else
            {
                var m = this.materialCb.Text;
                if (!m.IsNullOrEmpty())
                {
                    mWeighingBill.materialId = 0;
                    mWeighingBill.materialName = m;
                }
            }


            //车辆
            if (mWeighingBill.carId == null || mWeighingBill.carId <= 0 || string.IsNullOrEmpty(mWeighingBill.carNumber))
            {
                string carnum = this.carNumberCb.Text;
                if (App.Config.WeighingConfig.InNecessaryCar)
                {
                    if (carnum.IsNullOrEmpty() || carnum.Trim().IsNullOrEmpty())
                    {
                        string msg = "车辆信息不能为空";
                        Growl.Clear();
                        Growl.Warning(msg, "main");
                        this.saveBtn.IsChecked = false;
                        this.carNumberCb.Focus();
                        CommonFunction.SpeakAsync(msg);
                        return false;
                    }
                }

                if (App.Config.WeighingConfig.InCheckCarNumber)
                {
                    if (carnum.IsNullOrEmpty() || !RegexHelper.IsVehicleNumber(this.carNumberCb.Text))
                    {
                        string msg = "车牌号格式不正确";
                        Growl.Warning(msg, "main");
                        this.saveBtn.IsChecked = false;
                        this.carNumberCb.Focus();
                        CommonFunction.SpeakAsync(msg);
                        return false;
                    }
                }

                //不限止过磅，可以自动添加，或 随意过磅
                if (App.Config.WeighingConfig.CarLimit == 0)
                {
                    //是车辆格式 保存数据库
                    if (RegexHelper.IsVehicleNumber(carnum))
                    {
                        var car = new CarInfo()
                        {
                            id = IdHelper.LongID,
                            carNumber = this.carNumberCb.Text,
                            addTime = DateTime.Now,
                            addUserId = App.CurrentUser.id,
                            addUserName = App.CurrentUser.name,
                            remark = "自动添加",
                            traeWeight = mWeighingBill.traeWeight ?? 0,
                            driver = this.driverTb.Text,
                            driverMobile = this.phoneTb.Text
                        };
                        if (currCarVo == null)
                        {
                            currCarVo = new CarInfoVo(car);
                        }
                        mWeighingBill.carId = currCarVo.Id;
                        mWeighingBill.carNumber = currCarVo.CarNumber;
                        mWeighingBill.driver = currCarVo.Driver;
                        mWeighingBill.driverMobile = currCarVo.DriverMobile;
                    }
                    else
                    {
                        //非车辆格式 不保存 到 数据库
                        mWeighingBill.carId = 0;
                        mWeighingBill.driver = this.driverTb.Text;
                        mWeighingBill.carNumber = this.carNumberCb.Text;
                        mWeighingBill.driverMobile = this.phoneTb.Text;
                    }
                }
            }

            if (isOutFactory == false)
            {
                if (!CheckSelfCar(currCarVo?.mCarInfo))
                {
                    string msg = $"车辆 {currCarVo.CarNumber} 不是内部车辆，禁止过磅";
                    Growl.Clear();
                    Growl.Warning(msg, "main");
                    this.saveBtn.IsChecked = false;
                    this.carNumberCb.Focus();
                    CommonFunction.SpeakAsync(msg);
                    return false;
                }
            }

            if (App.Config.WeighingConfig.InNecessarySendWeighing && mWeighingBill.sendNetWeight <= 0)
            {
                string msg = "输入的原发净重数据错误，请重先输入。";
                CommonFunction.AlertInfo(msg);
                CommonFunction.SpeakAsync(msg);
                Growl.Info(msg, "main");
                this.saveBtn.IsChecked = false;
                this.sendNetWeightTb.Focus();
                return false;
            }
            mWeighingBill.moneyType = this.MoneyTypeCb.SelectedIndex;

            if (mWeighingBill.decuationDescription.IsNullOrEmpty())
            {
                mWeighingBill.decuationDescription = this.decuDescCb.Text;
            }
            return true;
        }
        //insert
        private void Insert()
        {
            int res;
            mWeighingBill.dataType = (int)DataType.Prod;

            //将备用字段的值，赋值到当前磅单
            GetBackFieldValue(this.inputCanvas);

            if (App.Config.WeighingConfig.Times == 2)
            {
                res = TwiceWeighingInsert();
            }
            else
            {
                res = OnceWeighingInsert();
                //更新受限次数
                if (res > 0)
                {
                    App.NoActiveLimits++;
                }
            }
            if (res > 0)
            {
                Growl.Clear();
                Growl.Success("保存成功", "main");
                BillNumberHelper.UpdateTodayCount((WeightingBillType)mWeighingBill.type);

                UpdateUsedBaseDataThread();

                SaveRemark(this.remarkCb, this.remarkCb.Text, true);

                CommonFunction.ClearLastRecognizePlate();

                //AutoSaveMatrial
                Task.Factory.StartNew(() =>
                {
                    this.UpdateSendBill();
                    Task.Delay(300);
                    MaterialDao.Instance.AutoSaveMatrial(currMaterialVo?.mMaterial);

                    if (currCarVo != null)
                    {
                        if (App.Config.WeighingConfig.OutTimes == 2)
                        {
                            currCarVo.TraeWeight = mWeighingBill?.traeWeight ?? 0;
                        }
                        CarDao.Instance.AutoSaveCarInfo(currCarVo.mCarInfo);
                    }
                });

                DataUcLoadData(currBillType);

                // CaptureJpeg              
                CommonFunction.CaptureJpeg(mWeighingBill.number, mWeighingBill.status.Value);
                if (App.Config.WeighingConfig.Times == 2)
                {
                    CommonFunction.SpeakAsync("保存成功");
                    //打印卸货单
                    if (App.Config.BillPrintConfig.EnableUnloadBill)
                    {
                        new PrintWindow(mWeighingBill?.id ?? 0, WeightingBillType.UnLoadingBill)
                        {
                            Owner = App.Current.MainWindow
                        }.Show();
                    }

                    this.inFactoryRb.IsChecked = false;
                    this.inFactoryRb.IsChecked = true;
                }
                else
                {
                    CommonFunction.SpeakAsync($"保存成功,{mWeighingBill.materialName} ,净重 {mWeighingBill.netWeight}{mWeighingBill.unitText}");
                    ToPrint();
                }
                mWeighingBill = null;
                BuildCurrWeighingBill();
            }
            else
            {
                var msg = "保存失败";
                Growl.Error(msg, "main");
                CommonFunction.SpeakAsync(msg);
            }
        }


        /// <summary>
        /// 一次过磅时 入场即为出场
        /// </summary>
        private int OnceWeighingInsert()
        {
            mWeighingBill.status = 1;
            mWeighingBill.userId = App.CurrentUser.id;
            mWeighingBill.outUserName = App.CurrentUser.name;
            mWeighingBill.inTime = null;
            mWeighingBill.outTime = DateTime.Now;
            mWeighingBill.addTime = mWeighingBill.outTime;
            mWeighingBill.addUserId = App.CurrentUser.id;
            mWeighingBill.addUserName = App.CurrentUser.name;
            mWeighingBill.syncTime = DateTimeHelper.GetTimeStamp();
            mWeighingBill.remark = this.remarkCb.Text;
            mWeighingBill.unitText = App.UnitText;
            if (App.Config.WeighingConfig.InIgnoreTraeWeighing == false)
            {
                if (mWeighingBill.traeWeight <= 0)
                {
                    Growl.Error("皮重吨位不正确", "main");
                    return 0;
                }
            }

            if (mWeighingBill.grossWeight <= 0)
            {
                Growl.Error("毛重吨位不正确", "main");
                return 0;
            }

            return WeighingBillDao.Instance.Insert(mWeighingBill);
        }
        /// <summary>
        /// 两次过磅时 的入场保存
        /// </summary>
        private int TwiceWeighingInsert()
        {
            mWeighingBill.status = 0;
            mWeighingBill.userId = App.CurrentUser.id;
            mWeighingBill.inUserName = App.CurrentUser.name;
            mWeighingBill.inTime = DateTime.Now;
            mWeighingBill.addTime = mWeighingBill.inTime;
            mWeighingBill.addUserId = App.CurrentUser.id;
            mWeighingBill.addUserName = App.CurrentUser.name;
            mWeighingBill.syncTime = DateTimeHelper.GetTimeStamp();
            mWeighingBill.remark = this.remarkCb.Text;
            mWeighingBill.unitText = App.UnitText;
            if (mWeighingBill.grossWeight <= 0)
            {
                Growl.Error("毛重吨位不正确", "main");
                return 0;
            }
            if (mWeighingBill.traeWeight <= 0 && isOutFactory)
            {
                Growl.Error("皮重吨位不正确", "main");
                return 0;
            }
            // 是否还有未完成的过磅
            bool has = WeighingBillDao.Instance.IsCarHasNofinishBill(currBillType, mWeighingBill.carNumber);
            if (has == true)
            {               
                string msg = $"车辆 {mWeighingBill.carNumber}还有未完成的过磅，不能进行新的过磅";
                CommonFunction.AlertInfo(msg);
                return 0;
            }
            var res = WeighingBillDao.Instance.Insert(mWeighingBill);
            return res;
        }

        /// <summary>
        /// 两次过磅 出场
        /// </summary>
        private void Update()
        {
            mWeighingBill.outTime = DateTime.Now;
            mWeighingBill.status = 1;
            mWeighingBill.userId = App.CurrentUser.id;
            mWeighingBill.outUserName = App.CurrentUser.name;
            mWeighingBill.syncTime = DateTimeHelper.GetTimeStamp();
            mWeighingBill.lastUpdateTime = mWeighingBill.outTime;
            mWeighingBill.lastUpdateUserId = App.CurrentUser.id;
            mWeighingBill.lastUpdateUserName = App.CurrentUser.name;
            mWeighingBill.remark = this.remarkCb.Text;
            mWeighingBill.dataType = (int)DataType.Prod;

            if (mWeighingBill.traeWeight <= 0 || mWeighingBill.netWeight <= 0)
            {
                Growl.Error("皮重,或者净重吨位不正确", "main");
                isSaveing = false;
                this.saveBtn.IsChecked = false;
                return;
            }

            //将备用字段的值，赋值到当前磅单
            GetBackFieldValue(this.inputCanvas);

            int res = WeighingBillDao.Instance.Update(mWeighingBill);
            if (res > 0)
            {
                //更新受限次数
                App.NoActiveLimits++;
                Growl.Clear();
                Growl.Success("保存成功！", "main");
                CommonFunction.SpeakAsync($"保存成功,{mWeighingBill.materialName},净重" + mWeighingBill.netWeight + mWeighingBill.unitText);

                CommonFunction.ClearLastRecognizePlate();

                ToPrint();

                UpdateUsedBaseDataThread();

                SaveRemark(this.remarkCb, this.remarkCb.Text, true);

                Task.Factory.StartNew(() =>
                {
                    UpdateSendBill();
                });


                DataUcLoadData(currBillType);
                //CaptureJpeg   
                CommonFunction.CaptureJpeg(mWeighingBill.number, mWeighingBill.status.Value);

                mWeighingBill = null;
                BuildCurrWeighingBill();
                this.inFactoryRb.IsChecked = true;
            }
            else
            {
                Growl.Error("保存磅单失败！", "main");
                CommonFunction.SpeakAsync("保存失败！");
                this.saveBtn.IsChecked = false;
            }
        }


        private void UpdateDecuationList()
        {
            Thread thread = new Thread(new ParameterizedThreadStart(CommonFunction.UpdateDecuationList));
            thread.Start(mWeighingBill.decuationDescription);
        }

        private void UpdateRemark()
        {
            Thread thread = new Thread(new ParameterizedThreadStart(CommonFunction.UpdateInputReamak));
            thread.Start(mWeighingBill.remark);
        }

        /// <summary>
        /// 更新发货单
        /// </summary>
        private void UpdateSendBill()
        {
        }

        #endregion

        #region 选择出场车辆

        /// <summary>
        /// 选择出场车辆
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WaitOutLv_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (this.waitOutLv.SelectedIndex < 0)
            {
                return;
            }
            if (this.waitOutLv.SelectedValue is WeighingBillVo bill)
            {
                OnCarSelected(bill.mWeighingBill);
            }
        }
        /// <summary>
        /// 选择出场车辆
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WaitOutLv_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (this.waitOutLv.SelectedIndex < 0)
                {
                    return;
                }
                if (this.waitOutLv.SelectedValue is WeighingBillVo bill)
                {
                    OnCarSelected(bill.mWeighingBill);
                }
            }
        }
        public void OnCarSelected(WeighingBill bill)
        {
            isOutFactory = true;
            if (IsRecongnizePlateWeighing == false)
            {
                Storyboard storyboard = new Storyboard();
                var anim = AnimationHelper.CreateAnimation(this.waitOutputBorder.ActualWidth);// enter from right
                Storyboard.SetTarget(anim, this.waitOutputBorder);
                Storyboard.SetTargetProperty(anim, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.X)"));
                storyboard.Children.Add(anim);

                var leftAni = AnimationHelper.CreateAnimation(0);
                Storyboard.SetTarget(leftAni, this.inputPanel);
                Storyboard.SetTargetProperty(leftAni, new PropertyPath("(UIElement.RenderTransform).(TranslateTransform.X)"));
                storyboard.Children.Add(leftAni);
                storyboard.Begin();
            }
            //动画结束，重置数据            
            mWeighingBill = bill;
            BuildCurrWeighingBill();
        }
        #endregion

        //搜索未出车辆
        private void SearchBar_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (sender is SearchBar searchBar && !searchBar.Text.IsNullOrEmpty() && this.noOutBills != null)
            {
                List<WeighingBillVo> temps = new List<WeighingBillVo>();
                var key = searchBar.Text.Trim();
                foreach (var item in this.noOutBills)
                {
                    if ((item.CarNumber ?? "").Contains(key)
                        || (item.MaterialName ?? "").Contains(key)
                        || (item.SendCompanyName ?? "").Contains(key)
                        || (item.ReceiveCompanyName ?? "").Contains(key))
                    {
                        temps.Add(item);
                    }
                }
                if (temps.Count > 0)
                {
                    this.waitOutLv.ItemsSource = null;
                    this.waitOutLv.ItemsSource = temps;
                }
                else
                {
                    this.waitOutLv.ItemsSource = null;
                    this.waitOutLv.ItemsSource = this.noOutBills;
                }
            }
            else
            {
                this.waitOutLv.ItemsSource = null;
                this.waitOutLv.ItemsSource = this.noOutBills;
            }
        }
        //读Ic卡
        private void ReadIcCardBtn_Click(object sender, RoutedEventArgs e)
        {

        }


        #region 隐藏的 锁定收货 改变事件
        private void LockReceiveCb_changed(object sender, RoutedEventArgs e)
        {
            SetDfaultCompany();
        }
        #endregion

        /// <summary>
        /// 打印
        /// </summary>
        private void ToPrint()
        {
            if (App.Config.BillPrintConfig.EnablePrintInBill)
            {
                var type = mWeighingBill?.status == (int)BillStatus.Finished
                      ? WeightingBillType.WeighintBill
                      : WeightingBillType.UnLoadingBill;

                if (App.Config.BillPrintConfig.IsUserExclCustomBill)
                {
                    new PrintEXCLWindow(mWeighingBill?.id ?? 0) { 
                    Owner = App.Current.MainWindow
                    }.ShowDialog();
                }
                else
                {
                    new PrintWindow(mWeighingBill?.id ?? 0, type)
                    {
                        Owner = App.Current.MainWindow
                    }.Show();
                }
            }
        }

        /// <summary>
        /// 显示扣重等信息
        /// </summary>
        public void ShowDecuationWeightView()
        {
            if (App.Config.WeighingConfig.Times == 1)
            {
                this.decuationWeightTb.Visibility = Visibility.Visible;
                this.decuDescCb.Visibility = Visibility.Visible;
                this.diffWeightTb.Visibility = Visibility.Visible;
            }
            else
            {
                if (this.outFactoryRb.IsChecked == true)
                {
                    this.decuationWeightTb.Visibility = Visibility.Visible;
                    this.decuDescCb.Visibility = Visibility.Visible;
                    this.diffWeightTb.Visibility = Visibility.Visible;
                }
                else
                {
                    this.decuationWeightTb.Visibility = Visibility.Collapsed;
                    this.decuDescCb.Visibility = Visibility.Collapsed;
                    this.diffWeightTb.Visibility = Visibility.Collapsed;
                }
            }
        }
        /// <summary>
        /// 过磅次数改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param> 
        private void TimesTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            ShowDecuationWeightView();
            ShowOrHidePricePanel();
            if (Convert.ToInt32(this.TimesTb.Text) == 1)
            {
                this.saveTraeBtn.Visibility = Visibility.Visible;
            }
            else
            {
                this.saveTraeBtn.Visibility = Visibility.Collapsed;
            }
        }

        #region 过磅设置
        private Popup weighingSettingPopup;
        //过磅设置
        private void WeighingSettingBtn_Click(object sender, RoutedEventArgs e)
        {
            if (weighingSettingPopup == null)
            {
                weighingSettingPopup = new Popup
                {
                    Placement = PlacementMode.Bottom,
                    PlacementTarget = this.weighingSettingBtn,
                    Name = "weighingSettingPopup",
                    StaysOpen = false,
                    VerticalOffset = 0,
                    HorizontalOffset = 10,
                    Child = new InWeighingSettingUc()
                };
            }
            weighingSettingPopup.IsOpen = !weighingSettingPopup.IsOpen;
        }

        #endregion

        //存皮
        private void SaveTraeBtn_Click(object sender, RoutedEventArgs e)
        {
            if (currCarVo == null || currCarVo.CarNumber.IsNullOrEmpty())
            {
                string msg = "未选择车辆信息。";
                CommonFunction.AlertInfo(msg);
            }
            else if (currTonner <= 1.5)
            {
                string msg = "当前的吨位太轻,小于1.5吨，不能保存。";
                CommonFunction.AlertInfo(msg);
            }
            else
            {
                string msg = $"是否要修改{currCarVo.CarNumber} 的皮重设置为{currTonner}。";
                var result = CommonFunction.Ask(msg);
                if (result == MessageBoxResult.Yes)
                {
                    currCarVo.TraeWeight = (decimal?)currTonner;
                    var c = new CarInfo
                    {
                        id = currCarVo.Id,
                        traeWeight = (decimal?)currTonner
                    };
                    int res = CarDao.Instance.Sqlite.Update(c);
                    if (res > 0)
                    {
                        CommonFunction.AlertInfo("保存成功！");
                        this.carNumberCb.Text = "";
                        this.carNumberCb.IsDropDownOpen = true;
                    }
                    else
                    {
                        CommonFunction.AlertInfo("保存失败！");
                    }
                }
            }
            this.saveTraeBtn.IsChecked = false;
        }

        #region lock weighing 锁定过磅
        private static readonly string lockGeomitryName = "LockFill";
        private static readonly string unLockGeomitryName = "UnLock";
        private Geometry lockG = App.Current.FindResource(lockGeomitryName) as Geometry;
        private Geometry unlockG = App.Current.FindResource(unLockGeomitryName) as Geometry;

        #region lock 发货公司
        /// <summary>
        /// 加载时候，初始锁定 发货公司 名称 按钮
        /// </summary>
        private void InitLockSendBtn()
        {
            CompanyVo lc = LockData.Instance.InLockSend;
            if (lc == null) App.Config.WeighingConfig.InLockSendCompany = false;
            this.lockSendBtn.IsEnabled = true;
            if (App.Config.WeighingConfig.InLockSendCompany)
            {
                //点击解锁
                this.lockSendBtn.ToolTip = LangHelper.Get(LangKeyNames.ClickUnLockName);
                IconElement.SetGeometry(this.lockSendBtn, lockG);
                this.lockSendBtn.Foreground = Brushes.PaleVioletRed;
                this.isSupplySelected = true;
                this.sendCompanyCb.IsEnabled = false;
                this.sendCompanyCb.Text = lc.FullName;
                sendCompanyVo = lc;
            }
            else
            {
                //点击锁定
                this.lockSendBtn.ToolTip = LangHelper.Get(LangKeyNames.ClickLockName);
                IconElement.SetGeometry(this.lockSendBtn, unlockG);
                this.lockSendBtn.Foreground = Brushes.Gray;
                this.isSupplySelected = false;
                this.sendCompanyCb.IsEnabled = true;
                this.sendCompanyCb.Text = "";
                sendCompanyVo = null;
            }
        }

        private void LockSendBtn_Click(object sender, RoutedEventArgs e)
        {
            string title = InfoElement.GetTitle(this.sendCompanyCb);
            string msg;
            CompanyVo lockSend = LockData.Instance.InLockSend;
            if (App.Config.WeighingConfig.InLockSendCompany)
            {
                //解锁
                if (lockSend == null)
                {
                    App.Config.WeighingConfig.InLockSendCompany = false;
                    CommonFunction.UpdateAppConfig(nameof(WeighingConfig));
                    InitLockSendBtn();
                }
                else
                {
                    //msg = $"是否取消{title} \n 为 {lockSend.FullName} 的锁定。";
                    msg = String.Format(LangHelper.Get(LangKeyNames.CancelLockTemplate), title, lockSend.FullName);
                    var res = CommonFunction.Ask(msg);
                    if (res == MessageBoxResult.Yes)
                    {
                        App.Config.WeighingConfig.InLockSendCompany = false;
                        CommonFunction.UpdateAppConfig(nameof(WeighingConfig));
                        LockData.Instance.InLockSend = null;
                        LockData.Instance.AsyncSaveToFile();
                        InitLockSendBtn();
                    }
                }
            }
            else
            {
                //锁定               
                if (sendCompanyVo == null)
                {
                    msg = String.Format(LangHelper.Get(LangKeyNames.LockSelectTemplate), title);
                    CommonFunction.AlertInfo(msg);
                    return;
                }
                else
                {
                    msg = String.Format(LangHelper.Get(LangKeyNames.LockTemplate), title, sendCompanyVo.FullName);
                    var result = CommonFunction.Ask(msg);
                    if (result == MessageBoxResult.Yes)
                    {
                        App.Config.WeighingConfig.InLockSendCompany = true;
                        CommonFunction.UpdateAppConfig(nameof(WeighingConfig));
                        LockData.Instance.InLockSend = sendCompanyVo;
                        LockData.Instance.AsyncSaveToFile();
                        InitLockSendBtn();
                    }
                }
            }
        }

        #endregion

        #region lock 收货公司
        /// <summary>
        /// 加载时候，初始锁定 收货公司 名称 按钮
        /// </summary>
        private void InitLockReceiveBtn()
        {
            //判定使用单位
            if (App.Config.WeighingConfig.InBindingReceive)
            {
                //已绑定为使用方信息
                this.lockReceiveBtn.ToolTip = LangHelper.Get(LangKeyNames.BindingedToUser);
                IconElement.SetGeometry(this.lockReceiveBtn, lockG);
                this.lockReceiveBtn.Foreground = Brushes.PaleVioletRed;

                this.isSelectReceiveCompany = true;
                this.RecevieCompanyCb.IsEnabled = false;
                this.RecevieCompanyCb.Text = App.CurrentCompanyVo.FullName;
                this.lockReceiveBtn.IsEnabled = false;
                return;
            }
            CompanyVo lc = LockData.Instance.InLockReceive;
            if (lc == null) App.Config.WeighingConfig.InLockReceiveCompany = false;
            if (App.Config.WeighingConfig.InLockReceiveCompany)
            {
                this.lockReceiveBtn.ToolTip = LangHelper.Get(LangKeyNames.ClickUnLockName);
                IconElement.SetGeometry(this.lockReceiveBtn, lockG);
                this.lockReceiveBtn.Foreground = Brushes.PaleVioletRed;
                this.isSelectReceiveCompany = true;
                this.RecevieCompanyCb.IsEnabled = false;
                this.RecevieCompanyCb.Text = lc.FullName;
                receiverCompanyVo = lc;
            }
            else
            {
                //this.lockReceiveBtn.ToolTip = "点击锁定";
                this.lockReceiveBtn.ToolTip = LangHelper.Get(LangKeyNames.ClickLockName);
                IconElement.SetGeometry(this.lockReceiveBtn, unlockG);
                this.lockReceiveBtn.Foreground = Brushes.Gray;
                this.isSelectReceiveCompany = false;
                this.RecevieCompanyCb.IsEnabled = true;
                this.RecevieCompanyCb.Text = "";
                receiverCompanyVo = null;
            }
        }

        private void LockReceiveBtn_Click(object sender, RoutedEventArgs e)
        {
            string title = InfoElement.GetTitle(this.RecevieCompanyCb);
            string msg;
            CompanyVo lc = LockData.Instance.InLockReceive;
            if (App.Config.WeighingConfig.InLockReceiveCompany)
            {
                //解锁
                if (lc == null)
                {
                    App.Config.WeighingConfig.InLockReceiveCompany = false;
                    CommonFunction.UpdateAppConfig(nameof(WeighingConfig));
                    InitLockReceiveBtn();
                }
                else
                {
                    //msg = $"是否取消{title} \n 为 {lc.FullName} 的锁定。";
                    msg = String.Format(LangHelper.Get(LangKeyNames.CancelLockTemplate), title, lc.FullName);
                    var res = CommonFunction.Ask(msg);
                    if (res == MessageBoxResult.Yes)
                    {
                        App.Config.WeighingConfig.InLockReceiveCompany = false;
                        CommonFunction.UpdateAppConfig(nameof(WeighingConfig));
                        LockData.Instance.InLockReceive = null;
                        LockData.Instance.AsyncSaveToFile();
                        InitLockReceiveBtn();
                    }
                }
            }
            else
            {
                //锁定               
                if (receiverCompanyVo == null)
                {
                    //msg = $"请选择好一个{title} 后再点击锁定。";
                    msg = String.Format(LangHelper.Get(LangKeyNames.LockSelectTemplate), title);
                    CommonFunction.AlertInfo(msg);
                    return;
                }
                else
                {
                    //msg = $"是否要将{title} \n 锁定为 {receiverCompanyVo.FullName}？";
                    msg = String.Format(LangHelper.Get(LangKeyNames.LockTemplate), title, receiverCompanyVo.FullName);
                    var result = CommonFunction.Ask(msg);
                    if (result == MessageBoxResult.Yes)
                    {
                        App.Config.WeighingConfig.InLockReceiveCompany = true;
                        CommonFunction.UpdateAppConfig(nameof(WeighingConfig));
                        LockData.Instance.InLockReceive = receiverCompanyVo;
                        LockData.Instance.AsyncSaveToFile();
                        InitLockReceiveBtn();
                    }
                }
            }
        }
        #endregion

        #region lock 物料名称

        /// <summary>
        /// 加载时候，初始锁定物料名称 按钮
        /// </summary>
        private void InitLockMaterialBtn()
        {
            MaterialVo lm = LockData.Instance.InLockMaterial;
            if (lm == null) App.Config.WeighingConfig.InLockMaterial = false;
            if (App.Config.WeighingConfig.InLockMaterial)
            {
                this.lockMaterialBtn.ToolTip = LangHelper.Get(LangKeyNames.ClickUnLockName);
                IconElement.SetGeometry(this.lockMaterialBtn, lockG);
                this.lockMaterialBtn.Foreground = Brushes.PaleVioletRed;
                this.isSelectMaterial = true;
                this.materialCb.IsEnabled = false;
                this.materialCb.Text = lm.Name;
                currMaterialVo = lm;
            }
            else
            {
                this.lockMaterialBtn.ToolTip = LangHelper.Get(LangKeyNames.ClickLockName);
                IconElement.SetGeometry(this.lockMaterialBtn, unlockG);
                this.lockMaterialBtn.Foreground = Brushes.Gray;
                this.isSelectMaterial = false;
                this.materialCb.IsEnabled = true;
                this.materialCb.Text = "";
                currMaterialVo = null;
            }
        }

        private void LockMaterialBtn_Click(object sender, RoutedEventArgs e)
        {
            string title = InfoElement.GetTitle(this.materialCb);
            string msg;
            MaterialVo lockMaterial = LockData.Instance.InLockMaterial;
            if (App.Config.WeighingConfig.InLockMaterial)
            {
                //解锁
                if (lockMaterial == null)
                {
                    App.Config.WeighingConfig.InLockMaterial = false;
                    CommonFunction.UpdateAppConfig(nameof(WeighingConfig));
                    InitLockMaterialBtn();
                }
                else
                {
                    // msg = $"是否取消{title} \n 为 {lockMaterial.Name} 的锁定。";
                    msg = String.Format(LangHelper.Get(LangKeyNames.CancelLockTemplate), title, lockMaterial.Name);
                    var res = CommonFunction.Ask(msg);
                    if (res == MessageBoxResult.Yes)
                    {
                        App.Config.WeighingConfig.InLockMaterial = false;
                        CommonFunction.UpdateAppConfig(nameof(WeighingConfig));
                        LockData.Instance.InLockMaterial = null;
                        LockData.Instance.AsyncSaveToFile();
                        InitLockMaterialBtn();
                    }
                }
            }
            else
            {
                //锁定               
                if (currMaterialVo == null)
                {
                    // msg = $"请选择好一个{title} 后再点击锁定。";
                    msg = String.Format(LangHelper.Get(LangKeyNames.LockSelectTemplate), title);
                    CommonFunction.AlertInfo(msg);
                    return;
                }
                else
                {
                    // msg = $"是否要将{title} \n 锁定为 {currMaterialVo.Name}？";
                    msg = String.Format(LangHelper.Get(LangKeyNames.LockTemplate), title, currMaterialVo.Name);
                    var result = CommonFunction.Ask(msg);
                    if (result == MessageBoxResult.Yes)
                    {
                        App.Config.WeighingConfig.InLockMaterial = true;
                        CommonFunction.UpdateAppConfig(nameof(WeighingConfig));
                        LockData.Instance.InLockMaterial = currMaterialVo;
                        LockData.Instance.AsyncSaveToFile();
                        InitLockMaterialBtn();
                    }
                }
            }
        }

        #endregion

        #endregion


        #region 模拟数据

        private void MoniWeighingCb_Checked(object sender, RoutedEventArgs e)
        {
            StartMoniTimer(WeightingBillType.Buy);
        }

        private void MoniWeighingCb_UnChecked(object sender, RoutedEventArgs e)
        {
            StopMoniTimer();
        }
        #endregion


        #region 运输公司

        private bool isSelectTranceCompany = false;

        private void TranceCompanyCb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (isOutFactory == true)
            {
                return;
            }
            String text = this.TranceCompanyCb.Text.Trim();
            if (text.Length < 2)
            {
                tranceCompanyVo = null;
                isSelectTranceCompany = false;
                this.TranceCompanyCb.IsDropDownOpen = false;
            }
            if (isSelectTranceCompany == true) { return; }
            if (text.Length >= 2)
            {
                List<Company> list = CompanyDao.Instance.SelectByNameOrFirstCaseLike(text);
                var data = list?.Select((i) => { return new CompanyVo(i); }).ToList();
                this.TranceCompanyCb.ItemsSource = data;
                isSelectTranceCompany = list?.Count > 0;
                if (this.TranceCompanyCb.ItemsSource != null)
                {
                    this.TranceCompanyCb.IsDropDownOpen = true;
                }
                else
                {
                    this.TranceCompanyCb.IsDropDownOpen = false;
                }
            }

        }

        private void TranceCompanyCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            isSelectTranceCompany = this.TranceCompanyCb.SelectedIndex > -1;
            tranceCompanyVo = TranceCompanyCb.SelectedItem as CompanyVo;
            if (tranceCompanyVo != null)
            {
                mWeighingBill.tranceCompanyId = tranceCompanyVo.Id;
                mWeighingBill.tranceCompanyName = tranceCompanyVo.FullName;
            }
        }
        #endregion

        #region 价格 计算机

        public void ShowOrHidePricePanel()
        {
            if (App.Config.WeighingConfig.Times == 2)
            {
                if (isOutFactory && App.Config.BillPrintConfig.InShowCalculate)
                {
                    this.PricePanel.Visibility = Visibility.Visible;
                }
                else
                {
                    this.PricePanel.Visibility = Visibility.Collapsed;
                }
            }
            else
            {
                if (App.Config.BillPrintConfig.InShowCalculate)
                {
                    this.PricePanel.Visibility = Visibility.Visible;
                }
                else
                {
                    this.PricePanel.Visibility = Visibility.Collapsed;
                }
            }
        }

        private void SetMaterialPrice()
        {
            if (mWeighingBill == null || mWeighingBill.materialId <= 0)
            {
                return;
            }


            //不管磅单是显示或者 不显示 都要计算 
            long mid = mWeighingBill.materialId ?? 0;
            MaterialPrice? materialPrice = MaterialPriceDao.Instance.GetMaterialCurrPrice(mid, MaterialPriceType.Sale);
            if (materialPrice == null)
            {
                mWeighingBill.priceId = 0;
                mWeighingBill.price = 0;
                mWeighingBill.totalMoney = 0;
                return;
            }
            mWeighingBill.priceId = (long)materialPrice.id;
            mWeighingBill.price = materialPrice.price;
            mWeighingBill.totalMoney = (decimal)Math.Round((double)(materialPrice.price * (mWeighingBill.netWeight ?? 0)), 3, MidpointRounding.AwayFromZero);

            this.TempPriceTb.Text = materialPrice.price + "";
        }

        private void TempPriceTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            mWeighingBill.price = 0;
            CalcMaterialMoney();
        }
        /// <summary>
        /// 计算货物的金额
        /// </summary>
        private void CalcMaterialMoney()
        {
            if (!IsLoaded || PricePanel.IsVisible == false) return;
            //不管磅单是显示或者 不显示 都要计算 
            decimal price = 0;
            try
            {
                price = Convert.ToDecimal(this.TempPriceTb.Text.Trim());
            }
            catch (Exception ex)
            {
                //    if(PricePanel.IsVisible)
                //        Growl.Error("输入的单价不正确，以0计算：" + ex.Message,"main");
            }


            mWeighingBill.priceId = 0;
            mWeighingBill.price = price;
            mWeighingBill.totalMoney = (decimal)Math.Round((double)(price * mWeighingBill.netWeight ?? 0), 3, MidpointRounding.AwayFromZero);


            this.TotalMoneyTb.Text = mWeighingBill.totalMoney + "";

            string receiveMoneyStr = this.ReceiveMoneyTb.Text.Trim();
            if (receiveMoneyStr.IsNullOrEmpty() || receiveMoneyStr.Equals("0")
                || receiveMoneyStr.Equals("0.0")
                || receiveMoneyStr.Equals("0.00")
                || receiveMoneyStr.Equals("0.000"))
            {
                this.ReceiveMoneyTb.Text = mWeighingBill.totalMoney + "";
            }
            else
            {
                mWeighingBill.receiveMoney = Convert.ToDecimal(receiveMoneyStr);
            }
        }

        private void ReceiveMoneyTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!IsLoaded) return;
            string receiveMoneyStr = this.ReceiveMoneyTb.Text.Trim();
            if (receiveMoneyStr.IsNullOrEmpty())
            {
                mWeighingBill.receiveMoney = 0;
            }
            else
            {
                mWeighingBill.receiveMoney = Convert.ToDecimal(receiveMoneyStr);
            }
        }


        private void MoneyTypeCb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!IsLoaded) return;
            if (this.MoneyTypeCb.SelectedIndex > -1)
            {
                mWeighingBill.moneyType = this.MoneyTypeCb.SelectedIndex;
            }
            else
            {
                mWeighingBill.moneyType = 0;
            }
        }
        #endregion




        #region override

        public override void OnDefaultScaleHouseChanged(ScaleHouseVo vo)
        {
            if (vo == null) return;
            this.currHouseTb.Text = vo?.Name ?? "";
        }


        public override void OnBillSettingChanged()
        {
            this.billnumberTb.IsReadOnly = App.Config.BillPrintConfig.AutoGeneretor;
            this.billnumberTb.IsEnabled = !App.Config.BillPrintConfig.AutoGeneretor;
            SetBillNumber();
        }

        public override void OnIgnoreTraeChanged()
        {
            if (App.Config.WeighingConfig.InIgnoreTraeWeighing)
            {
                this.saveTraeBtn.Visibility = Visibility.Collapsed;
                //this.TraeWeightTb.Text = "0";
                //this.TraeWeightTb.Visibility = Visibility.Collapsed;
            }
            else
            {
                this.saveTraeBtn.Visibility = Visibility.Visible;
                //this.TraeWeightTb.Visibility = Visibility.Visible;
            }
        }

        public override void OnBackupBillFieldChangedHandle(BackupBillField backupBillField)
        {
            //备用字段改变
            if (backupBillField.billType == (int)WeightingBillType.Buy)
            {
                UpdateBackFieldTextBox(backupBillField, this.inputCanvas);
            }

        }
        #endregion
        private void SetBillNumber()
        {
            currBillNumber = GetWeighingNumber();
            this.billnumberTb.Text = currBillNumber;
            if (mWeighingBill != null)
            {
                mWeighingBill.number = currBillNumber;
            }
        }

        public override Canvas GetCanvas()
        {
            return this.inputCanvas;
        }


        #region 车牌号输入

        private void KeyBoardBtn_Click(object sender, RoutedEventArgs e)
        {
            this.carInputPopup.IsOpen = !this.carInputPopup.IsOpen;
            if (this.carInputPopup.IsOpen)
            {
                this.carNumberInput.Complated += On_Complated;
            }
            else
            {
                this.carNumberInput.Complated -= On_Complated;
            }
        }

        private void On_Complated(string res)
        {
            this.carNumberCb.Text = res;
            this.carInputPopup.IsOpen = false;
        }
        #endregion

        private void DataLenghtTb_TextChanged(object sender, TextChangedEventArgs e)
        {
            SetDefaultSource();
        }
    }
}
